<template>
	<view class="hudong">
		<u-navbar :border-bottom="false" title="互动" back-icon-name="camera" :custom-back="chooseImages" :custom-share="share" use-back-icon-name use-share ></u-navbar>
		<view class="container" v-if="hudongData.length > 0">
			<view class="item acea-row" v-for="(item,index) in hudongData" :key="index">
				<view class="tx"><image :src="baseUrl + item.headimg" mode=""></image></view>
				<view class="right">
					<view class="name">{{item.truename}}</view>
					<u-read-more text-indent='0' show-height='400' toggle='true'>
						<rich-text class="content" :nodes="item.content"></rich-text>
					</u-read-more>
					<view class="imgList">
						<view class="imgOne" v-if="item.media_file.length == 1">
							<image v-if="!checkVideoUrl(item.media_file[0])" :src="item.media_file[0]" @load="(e)=>imageDeal(e,index)" :style="'width: '+item.imgWidth+'rpx;height: '+item.imgHeight+'rpx;'" @click="previewImage(index,0)" mode="aspectFill"></image>
							<video @click="doPreviewVideo(item.media_file[0])" v-else :src="item.media_file[0]" :controls="false" ></video>
						</view>
						<view class="imgMany acea-row" v-if="item.media_file.length > 1">
							<view v-for="(itemImg,indexImg) in item.media_file" :key="indexImg">
								<image v-if="!checkVideoUrl(itemImg)" :src="itemImg" :style="'width: '+rightContentSize+'rpx;height: '+rightContentSize+'rpx;'" @click="previewImage(index,indexImg)" mode="aspectFill"></image>
								<video @click="doPreviewVideo(itemImg)" v-else :src="itemImg" :controls="false" :style="'width: '+rightContentSize+'rpx;height: '+rightContentSize+'rpx;'"></video>
							</view>
						</view>
					</view>
					<view class="info acea-row row-middle row-between">
						<view class="time">{{item.dateline}}</view>
						<view class="gongneng acea-row row-middle row-center" @click.stop="itemMove(index)">
							<view class="ball" style="margin-right: 10rpx;"></view>
							<view class="ball"></view>
							<view class="features-block" :style="'width: '+item.featuresWidth+'rpx;transition: width .3s;'">
								<view class="features acea-row row-middle row-between" @click.stop>
									<view class="f-item acea-row row-middle" @click.stop="() => showHuifu(item.id,index)">
										<u-icon name="chat" color="#ffffff" size="38" style="margin-right: 12rpx;"></u-icon>
										<text>评论</text>
									</view>
									<view class="f-item acea-row row-middle" @click.stop="() => delHudong(item.id)">
										<u-icon name="minus-circle" color="#ffffff" size="38" style="margin-right: 12rpx;"></u-icon>
										<text>删除</text>
									</view>
								</view>
							</view>
						</view>
						<view class="zanANDpinglun">
							<view class="zanList acea-row row-middle" v-if="item.click">
								<u-icon name="heart" color="#4E6086" size="32" style="margin-right: 6rpx;margin-bottom: 10rpx;"></u-icon>
								<text class="line1" v-for="(itemZan,indexZan) in item.click" :key="indexZan">{{itemZan}}{{item.click[indexZan+1]?',':''}}</text>
							</view>
							<view class="pinlun" v-if="item.comment.length > 0" :style="item.click?'border-top: 2rpx solid #e5e5e5;':''">
								<view class="pinlun-item" :class="'pinlun'+item.id+'-'+indexPl" :style="itemPl.isCheck?'background-color: #ebebeb;':''" v-for="(itemPl,indexPl) in item.comment" @click.stop="() => showHuifu(item.id,index,itemPl.id,itemPl.name,itemPl.jw_teacher_id,indexPl)" :key="indexPl">
									<text class="pinlun-item-left">
										{{itemPl.name}}<text v-show="itemPl.replay" style="color: #1f2329;">回复</text>{{itemPl.replay?itemPl.replay+':':':'}}
									</text>
									<text class="pinlun-item-right">
										{{itemPl.content}}
									</text>
									<view class="del" :style="itemPl.isCheck?'z-index:1000;':''" v-show="itemPl.isCheck&&hudongStatus==2" @click="del(itemPl.id,index)">删除</view>
								</view>
							</view>
						</view>
					</view>
					<!-- <view class="share acea-row row-middle row-center" @click.stop="share">
						<u-icon name="share" color="#1f2329" size="42"></u-icon>
					</view> -->
				</view>
			</view>
			<u-loadmore :status="status" style="margin-top: 10rpx;display: block;" />
		</view>
		<u-empty text="暂无互动" mode="list" v-else margin-top="32"></u-empty>
		<view style="height: 32rpx;"></view>
		<view class="huifuView" v-show="show">
			<view class="mark" @touchstart="markTouchstart" @click="closeHf"></view>
			<u-search ref="huifu" v-if="hudongStatus == 1&&show" class="pinlun acea-row row-middle" 
				:placeholder="huifuPlace" 
				shape="square" 
				@custom="fsPinglun" 
				:style="'width: 100%;z-index: 10;bottom:'+bottom+'px;'" 
				focus 
				action-text="发送" 
				bg-color="#ffffff" 
				:adjustPosition="false"
				confirmType="确认"
				search-icon=""></u-search>
		</view>
		<previewVideo :show.sync="showPreviewVideo" :url="previewVideoUrl"></previewVideo>
	</view>
</template>

<script>
	const app = getApp()
	import common from '../../api/common.js'
	import request from '../../api/request.js'
	const action = app.globalData.uploadUrl.zuoye
	export default{
		data(){
			return{
				canSocket:false,
				canShow:true,
				common,
				id:'', //课后点评的id
				parent_id:0, //上级评论的id，没有填0
				baseUrl:app.globalData.baseUrl,
				status:'loadmore',
				page:1,
				limit:10,
				hudongData:[],
				rightWidth:588,
				rightContentWidth:400, // 限制的宽度
				rightContentHeight:400, // 限制的高度
				rightContentSize:188, // 宽高相等时限制的宽度的，间隔12rpx
				imgWidth:0,
				imgHeight:0,
				featuresWidth:0,
				show:false,
				hudongStatus:1,
				bottom:0, //键盘弹起底部高度(px)
				pinlunTop:0, //选中的评论top(px)
				bodyTop:0, //页面top(px)
				timer:null, //函数节流
				huifuIndex:-1, //选中的回复index
				huifuPlace:'评论',
				content:'山不在高，有仙则名。水不在深，有龙则灵。斯是陋室，惟吾德馨。苔痕上阶绿，草色入帘青。谈笑有鸿儒，往来无白丁。可以调素琴，阅金经。无丝竹之乱耳，无案牍之劳形。南阳诸葛庐，西蜀子云亭。孔子云：何陋之有？',
			
				showPreviewVideo:false,
				previewVideoUrl:'',
			}
		},
		onShow() {
			//webSocket连接
			this.connectSocket()
			if(this.canShow){
				this.init()
			}else{
				this.canShow = true
			}
		},
		mounted() {
			// 计算键盘高度
			uni.onKeyboardHeightChange(res => {
				// console.log("计算键盘高度",res.height,app.globalData.screenHeight)
				// this.bottom = res.height==0?0:(res.height - 52)
				if(this.bottom < app.globalData.screenHeight/2){
					this.bottom = res.height==0?0:(res.height - 52)
				}
			})
		},
		methods:{
			init(){
				this.hudongData = []
				this.page = 1
				this.getHuDongData()
			},
			getHuDongData(){
				this.status = 'loading';
				let data = {
					page:this.page,
					limit:this.limit
				}
				request.go((e)=>{
					this.status = 'loadmore';
					uni.stopPullDownRefresh()
					for(let i in e.data){
						e.data[i].featuresWidth = 0
						e.data[i].imgWidth = 0
						e.data[i].imgHeight = 0
						for (let j in e.data[i].media_file){
							e.data[i].media_file[j] = this.baseUrl + e.data[i].media_file[j]
						}
						for(let j of e.data[i].comment){
							j.isCheck = false
						}
					}
					if(e.data.length == 0){
						this.status = 'nomore'
					}else{
						this.hudongData = this.hudongData.concat(e.data)
					}
				},'/comment/index',data,'POST')
			},
			previewImage(idx,current){
				// idx,item下标值
				// console.log('previewImage',this.hudongData[idx].media_file,idx)
				let file = [];
				for(let i of this.hudongData[idx].media_file){
					if(!app.globalData.checkVideoUrl(i)){
						file.push(i)
					}
				}
				uni.previewImage({
					urls:file,
					current
				})
				this.canShow = false
			},
			fsPinglun(e){
				let data = {
					grow_id:this.id,
					parent_id:this.parent_id,
					content:e
				}
				// 发送评论
				request.go((e)=>{
					this.show = false
					let f = this.hudongData.find(o=>o.id == this.id)
					for(let i of f.comment){
						i.isCheck = false
					}
					// 静态生成评论
					e.data.name = app.globalData.userInfo.nickname
					f.comment.push(e.data)
					//生成Socket data
					let socketData = {
						id:this.id,
						user_id:app.globalData.userInfo.id,
						name:e.data.name,
						replay:e.data.replay,
						content:e.data.content
					}
					console.log("socketData",socketData)
					this.sendSocketMessage(socketData)
				},'/Comment/addComment',data,'POST')
			},
			delHudong(id){ // 删除互动
				uni.showLoading({
					title:'删除中'
				})
				request.go((e)=>{
					uni.hideLoading()
					uni.showToast({
						title:'删除成功',
						icon:'none'
					})
					this.init();
				},'/comment/del',{id},'POST')
			},
			del(id,index){ // 删除评论
				request.go((e)=>{
					let idx = this.hudongData[index].comment.findIndex(e=>e.id==id)
					this.hudongData[index].comment.splice(idx,1)
					this.show = false
				},'/comment/deleteComment',{id},'POST')
			},
			chooseImages(){
				const that = this
				uni.chooseImage({
					count:9,
					success(e) {
						setTimeout(()=>{
							uni.showLoading({
								title:'图片上传中',
								mask:true
							})
						},300)
						console.log(e)
						// let hudongFiles = []
						let files = JSON.parse(JSON.stringify(e.tempFilePaths))
						// for(let i of files){
						// 	hudongFiles.push({url:i})
						// }
						that.uploadFile(e.tempFilePaths).then(res=>{
							console.log("res",res)
							// 将得到的互动图片数组保存到globalData
							app.globalData.hudongImgList = res.arr
							app.globalData.hudongFiles = res.hudongFiles
							// that.common.go('/pages/class/classRecord?showToast='+1)
							that.common.go('/pages/pack/hudong/setHudong2')
						})
					}
				})
			},
			uploadFile(files){
				// 图片上传
				return new Promise((resolve, reject)=>{
					let arr = []
					let fLength = files.length
					let hudongFiles = []
					
					for(let i of files){
						uni.uploadFile({
							url:action,
							filePath:i,
							name:'zyfile',
							header:{
								"Content-Type":"application/x-www-form-urlencoded"
							},
							formData:{
								token:app.globalData.userInfo.token
							},
							success(e){
								// console.log('uploadFile',e,JSON.parse(e.data))
								let res = JSON.parse(e.data)
								if(res.code == 200){
									arr.push(res.data.id)
									hudongFiles.push({url:i})
								}else{
									uni.showToast({
										icon:"none",
										title:res.message,
										duration:800
									})
									fLength--;
								}
								if(arr.length == fLength && arr.length != 0){
									setTimeout(()=>{
										uni.hideLoading()
										resolve({arr,hudongFiles})
									},800)
								}
							},
							fail(err) {
								// console.log(err)
								uni.hideLoading()
								uni.showToast({
									icon:'none',
									title:'图片上传错误'
								})
							}
						})
					}
				})
			},
			imageDeal(e,idx){
				// console.log(e)
				// 单图图片处理
				let width = e.detail.width,
					height = e.detail.height,
					imgWidth = e.detail.width,
					imgHeight = e.detail.height;
				// 如果宽大于高
				if(width > height){
					// 宽大于rightContentWidth,则等于rightContentWidth,否则为原宽高
					if(width >= this.rightContentWidth){
						imgWidth = this.rightContentWidth
						imgHeight = Math.round(this.rightContentWidth*height/width)
					}
				}else if(width == height){
					if(width >= this.rightContentSize){
						imgWidth = this.rightContentSize
						imgHeight = this.rightContentSize
					}
				}else{
					// 优先判断限制的高度
					if(height >= this.rightContentHeight){
						imgHeight = this.rightContentHeight
						imgWidth = Math.round(this.rightContentHeight*width/height)
					}else{
						// 在高度范围内的，判断宽度是否超过限制
						if(width >= this.rightContentSize){
							imgWidth = this.rightContentSize
							imgHeight = Math.round(this.rightContentSize*height/width)
						}
					}
				}
				this.hudongData[idx].imgWidth = imgWidth
				this.hudongData[idx].imgHeight = imgHeight
				// console.log(imgWidth,imgHeight,this.hudongData[idx].imgWidth)
			},
			showHuifu(id,index,parent_id=0,name='',jw_teacher_id=-1,plIndex=-1){
				// console.log(id,index,parent_id,name,jw_teacher_id,plIndex)
				this.show = true
				this.huifuIndex = plIndex
				if(plIndex != -1){
					this.hudongData.find(e=>e.id == id).comment[plIndex].isCheck = true
				}
				//回复判断，注意jw_teacher_id==自己id时显示删除
				// 1显示回复框和遮罩层,2只显示遮罩层不显示恢复框
				if(jw_teacher_id == app.globalData.userInfo.id){
					this.hudongStatus = 2
				}else{
					this.hudongStatus = 1
				}
				this.id = id
				this.parent_id = parent_id
				if(name){
					this.huifuPlace = '回复'+name
				}else{
					this.huifuPlace = '评论'
				}
				this.hudongData[index].featuresWidth = 0
			},
			scrollTo(){
				// 键盘弹起时移动页面
				// 变量x = 窗口高度screenHeight - bottom - pinlun高度 - pinlunTop - 底部评论框高 - 底部tabbar高度 ,用px,x需要变化的高度 
				let systemInfo = uni.getSystemInfoSync();
				let x = Math.floor(systemInfo.screenHeight) - Math.floor(this.bottom) - 50 - Math.floor(this.pinlunTop) - 20 - 50 - 12
				let scrollTop = this.bodyTop - x
				// console.log(scrollTop,x,this.bottom,this.pinlunTop,this.bodyTop,systemInfo.screenHeight,systemInfo)
				uni.pageScrollTo({scrollTop})
			},
			closeHf(){
				// console.log('closeHf')
				let f = this.hudongData.find(o=>o.id == this.id)
				for(let i of f.comment){
					i.isCheck = false
				}
				this.show = false
			},
			markTouchstart(){
				this.closeHf()
			},
			itemMove(index){
				this.hudongData[index].featuresWidth = this.hudongData[index].featuresWidth==0?340:0
			},
			// WebSocket 方法
			connectSocket(){
				const that = this
				uni.connectSocket({
				    url: '',
				});
				uni.onSocketOpen(function (res) {
				  console.log('WebSocket连接已打开！');
				  that.canSocket = true
				});
				uni.onSocketMessage(function (res) {
					console.log('收到服务器内容：' + res.data);
					if(that.canSocket){
						let data = JSON.parse(res.data)
						//生成静态评论
						if(app.globalData.userInfo.id != data.user_id){
							let f = that.hudongData.find(o=>o.id == data.id)
							if(f){
								let view = {
									content:data.content,
									name:data.name
								}
								if(data.replay == null){
									view.reply = null
								}else{
									view.replay = data.replay
								}
								f.comment.push(view)
							}
						}
					}
				});
				uni.onSocketClose(function(e){
					console.log('websocket 断开：' + e.code + ' ' + e.reason + ' ' + e.wasClean)
				})
			},
			sendSocketMessage(msg){
				if(this.canSocket){
					uni.sendSocketMessage({
					data:JSON.stringify(msg)
					})
				}
			},
			doPreviewVideo(url){
				this.showPreviewVideo = true;
				this.previewVideoUrl = url;
			},
			checkVideoUrl(url){
				if(url != undefined){
					return app.globalData.checkVideoUrl(url)
				}
			},
			share(){
				uni.previewImage({
					current:0,
					urls:[app.globalData.config.hudong_share],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
						},
					}
				})
			},
		},
		onReachBottom() {
			if(this.status == "loadmore"){
				this.page = ++ this.page;
				this.getHuDongData()
			}
		},
		onPullDownRefresh(){
			this.init()
		},
		onPageScroll(e){
			this.bodyTop = Math.floor(e.scrollTop)
			// if (timer){clearTimeout(timer)};
			// this.timer = setTimeout(() => {
				// console.log(e)
			// }, 10)
		},
		watch:{
			bottom(num){
				clearTimeout(this.timer)
				this.timer = setTimeout(()=>{
					if(num > 0&&this.huifuIndex!=-1){
						const that = this
						let id = this.id
						let index = this.huifuIndex
						const query = uni.createSelectorQuery()
						let className = '.pinlun'+id+'-'+index
						query.select(className).boundingClientRect((data)=>{
							// console.log(data,className)
							that.pinlunTop = data.top
							this.scrollTo()
						}).exec()
					}
				},300)
			}
		},
		created() {
			
		},
		onHide() {
			uni.closeSocket()
		}
	}
</script>

<style scoped>
	.hudong{
		min-height: 100vh;
		background-color: #FFFFFF;
	}
	.hudong .container{
		min-height: 100vh;
	}
	.hudong .container .item{
		padding: 32rpx;
		border-bottom: 2rpx solid #f6f6f6;
		flex-wrap: nowrap;
	}
	.hudong .container .item:last-of-type{
		border-bottom: none;
	}
	.hudong .container .item .tx{
		width: 80rpx;
		height: 80rpx;
		border-radius: 16rpx;
	}
	.hudong .container .item .tx image{
		display: block;
		width: 100%;
		height: 100%;
	}
	.hudong .container .item .right{
		/* 750 - 32*2 - 80 - 18 =  */
		margin-left: 18rpx;
		width: 588rpx;
		position: relative;
	}
	.hudong .container .item .right .share{
		position: absolute;
		width: 80rpx;
		height: 80rpx;
		right: 0rpx;
		top: 0rpx;
	}
	.hudong .container .item .right .name{
		color: #4E6086;
		font-size: 34rpx;
		margin-bottom: 20rpx;
		font-weight: bold;
		line-height: 34rpx;
	}
	.hudong .container .item .right >>> .content{
		font-size: 30rpx;
		color: #1f2329;
	}
	.hudong .container .item .right .imgList{
		width: 100%;
		margin-top: 20rpx;
	}
	.hudong .container .item .right .imgList .imgOne image{
		max-width: 100%;
	}
	.hudong .container .item .right .imgList .imgMany view{
		margin-right: 12rpx;
		margin-bottom: 12rpx;
	}
	.hudong .container .item .right .imgList .imgMany view:nth-child(3n){
		margin-right: 0;
	}
	.hudong .container .item .right .info{
		margin-top: 20rpx;
	}
	.hudong .container .item .right .info .time{
		color: #c0c4cc;
	}
	.hudong .container .item .right .info .gongneng{
		width: 90rpx;
		height: 45rpx;
		background-color: #F8F8F8;
		border-radius: 6rpx;
		position: relative;
	}
	.hudong .container .item .right .info .gongneng .ball{
		background-color: #61668c;
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
	}
	.hudong .container .item .right .info .gongneng .features-block{
		position: absolute;
		height: 76rpx;
		right: calc(100% + 20rpx);
		top: 50%;
		transform: translateY(-50%);
		overflow: hidden;
	}
	.hudong .container .item .right .info .gongneng .features{
		width: 340rpx;
		height: 76rpx;
		padding: 0 32rpx;
		background-color: #4c4c4c;
		border-radius: 8rpx;
		box-sizing: border-box;
	}
	.hudong .container .item .right .info .gongneng .features .f-item{
		color: #FFFFFF;
		font-size: 28rpx;
		line-height: 28rpx;
	}
	.hudong .container .item .right .info .zanANDpinglun{
		width: 100%;
		margin-top: 20rpx;
		background-color: #f7f7f7;
		border-radius: 6rpx;
		box-sizing: border-box;
		color: #4E6086;
	}
	.hudong .container .item .right .info .zanANDpinglun .zanList{
		padding: 12rpx 24rpx 0 24rpx;
		box-sizing: border-box;
	}
	.hudong .container .item .right .info .zanANDpinglun .zanList text{
		font-size: 30rpx;
		line-height: 30rpx;
		margin: 0 6rpx 12rpx 6rpx;
		font-weight: bold;
		max-width: 450rpx;
	}
	.hudong .container .item .right .info .zanANDpinglun .pinlun{
		padding: 12rpx 24rpx;
		box-sizing: border-box;
		font-size: 30rpx;
	}
	.hudong .container .item .right .info .zanANDpinglun .pinlun .pinlun-item{
		word-break: break-all;
		margin-bottom: 16rpx;
		position: relative;
		/* height: 20px; */
	}
	.hudong .container .item .right .info .zanANDpinglun .pinlun .pinlun-item .del{
		position: absolute;
		/* top: calc(-100% - 50rpx); */
		bottom: 100%;
		right: 0;
		width: 140rpx;
		box-sizing: border-box;
		padding: 20rpx;
		color: #303133;
		background-color: #FFFFFF;
		box-shadow: 0px 0px 1px rgba(20, 20, 20, 0.08), 0px 1px 8px 2px rgba(20, 20, 20, 0.08);
	}
	.hudong .container .item .right .info .zanANDpinglun .pinlun .pinlun-item:last-of-type{
		margin-bottom: 0;
	}
	.hudong .container .item .right .info .zanANDpinglun .pinlun .pinlun-item .pinlun-item-left{
		color: #4E6086;
		font-size: 30rpx;
		font-weight: bold;
	}
	.hudong .container .item .right .info .zanANDpinglun .pinlun .pinlun-item .pinlun-item-right{
		color: #1f2329;
	}
	.hudong .huifuView{
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
	}
	.hudong .huifuView .mark{
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 5;
	}
	.hudong .huifuView .pinlun{
		position: absolute;
		z-index: 10;
		/* bottom: 0; */
		left: 0;
		width: 100%;
		height: 100rpx;
		background-color: #f7f7f7;
		padding: 0 32rpx;
		box-sizing: border-box;
		transition: bottom 0.3s ease-in-out .3s;
	}
</style>
